import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:proj_sfv/http/api.dart';
import 'package:proj_sfv/http/requests.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_conversation_view_model.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_friendship_view_model.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/controller/tim_uikit_conversation_controller.dart';

class LoginPage extends StatefulWidget {
  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  bool _loginning = false;
  TUIFriendShipViewModel model = serviceLocator<TUIFriendShipViewModel>();
  TUIConversationViewModel conversationViewModel = serviceLocator<TUIConversationViewModel>();

  @override
  void dispose() {
    usernameController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  Future<void> timLogin(int id, String sig) async {
    final instance = TIMUIKitCore.getInstance();
    final V2TIMManager _sdkInstance = TIMUIKitCore.getSDKInstance();
    var resp = await instance.init(
        sdkAppID: 1400795083,
        loglevel: LogLevelEnum.V2TIM_LOG_ERROR,
        listener: V2TimSDKListener()
    );
    if (resp) {
      //初始化成功
      print('初始化成功');
    }
    V2TimCallback callback = await instance.login(userID: id.toString(), userSig: sig);
    if (callback.code != 0) {
      Fluttertoast.showToast(msg: '登陆失败，错误信息${callback.desc}');
      print('登陆失败，错误信息${callback.desc}');
    } else {
      Fluttertoast.showToast(msg: "登陆成功，信息为${callback.desc}");
      model.loadData();
      conversationViewModel.loadData(count: 100);
    }
  }

  void tryRegister() async {
    var result = await Navigator.pushNamed(context, "/user/register") as Map<String, String>;
    setState(() {
      _loginning = true;
    });
    if (result != null) {
      SharedPreferences.getInstance().then((value) async {
        value.setString("token", result['token']);
        value.setInt("id", int.parse(result['id']));
        var sig = result['sig'];
        value.setString("sig", sig);
        await timLogin(int.parse(result['id']), sig);
        int gender = result['gender'] == "true" ? 1 : 0;
        await TencentImSDKPlugin.v2TIMManager.setSelfInfo(userFullInfo: V2TimUserFullInfo(allowType: 1,
            nickName: result['userName'], gender: gender, faceUrl: 'https://$cosHost/${result['profile']}.jpg'));
      });
      Future.delayed(Duration(seconds: 5), () => Navigator.pop(context, "success"),);
    }
    setState(() {
      _loginning = true;
    });
  }

  void tryLogin() async {
    setState(() {
      _loginning = true;
    });
    var username = usernameController.value.text;
    var password = passwordController.value.text;
    var resp = await loginRequest(context, username, password);
    if (resp != null) {
      SharedPreferences.getInstance().then((value) async {
        value.setString("token", resp['token']);
        var id = int.parse(resp['id']);
        value.setInt("id", id);
        var sig = resp['sig'];
        value.setString("sig", sig);
        await timLogin(id, sig);
      });
      // Navigator.pop(context, "success");
      Future.delayed(Duration(seconds: 3), () => Navigator.pushNamedAndRemoveUntil
        (context, "/home", (route) => route == null));

    }
    else {
      setState(() {
        _loginning = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    // 加载本地封面图
    var image2 = AssetImage("assets/agia_vavatsinia.jpeg");
    return Scaffold(
      appBar: AppBar(
        title: Text("登陆"),
      ),
      body: Stack(
        children: [
          Form(
          key: _formKey,
          child: Column(
            children: [
              SizedBox(
                height: 200,
                child: Container(
                  height: 160,
                  decoration: BoxDecoration(
                      image: DecorationImage(image: image2, fit: BoxFit.cover)
                  ),
                )
              ),
              SizedBox(height: 30,),
              Column(
                children: [
                  TextField(
                    decoration: InputDecoration(
                      label: Text("用户名"),
                      border: const OutlineInputBorder(),
                    ),
                    controller: usernameController,
                  ),
                  SizedBox(height: 20,),
                  TextField(
                    decoration: InputDecoration(
                      label: Text("密码"),
                      border: const OutlineInputBorder(),
                    ),
                    obscureText: true,
                    controller: passwordController,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                          mainAxisSize: MainAxisSize.max,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            ElevatedButton(
                              // color: ,
                              onPressed: () => tryLogin(),
                              child: Text("登陆"),
                            ),
                            SizedBox(width: 10,),
                            ElevatedButton(
                              onPressed: () => tryRegister(),
                              child: Text("注册"),
                            )
                          ],
                        )
                  ),
                ],
              ),
          ],),
        ),
          Visibility(
            visible: _loginning,
            child: Positioned(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.black26,
                    boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.8),
                      spreadRadius: 5,
                      blurRadius: 7,
                      offset: Offset(0, 3), // changes position of shadow
                    ),
                    ],
                  ),
                  child: Center(
                    child: CircularProgressIndicator(
                    ),
                  ),
                ),
            ),
          )
        ]
      )
    );
  }


}